package game.server;

public class Latch {
	private final Object lock;
	private int count;
	private ServerTable serverTable;
	private boolean open;
	/**
	 * Constructor for latch.
	 * Initializes synchronized object.
	 * Sets latchcount to count.
	 * @param count How many threads to wait
	 */
	public Latch(int count, ServerTable serverTable) {
		this.lock = new Object();
		this.serverTable = serverTable;
		synchronized (lock) {
			this.count = count;
			this.open = false;
		}
	}
	/**
	 * Count one thread down from the countdown list
	 * and notify all.
	 */
	public void countDown() {
		synchronized (lock) {
			count--;
			if (count <= 0) {
				lock.notifyAll();
				open = true;
			} 
		} 
	}
	/**
	 * Thread left. Important when game hasn't started for the first time.
	 */
	public void leave() {
		synchronized (lock) {
			count++;
			if (count <= 0) {
				lock.notifyAll();
			} 
		} 
	}
	/**
	 * Wait until countdown reaches to zero.
	 * @throws InterruptedException
	 */
	public void await() throws InterruptedException {
		synchronized (lock) {
			while (count > 0) {
				lock.wait();
				serverTable.emptyWaitlistBuffer();
			} 
		} 
	}
	/**
	 * Is this latch opened or not.
	 * @return open.
	 */
	public boolean isOpen() {
		synchronized (lock) {
			return this.open;
		}
	}
}
